<!DOCTYPE html>
<html lang="zh-cn">
  
  <head>
    <meta charset="UTF-8" />
    <title>
      放大镜效果
    </title>
    <style>
      .box1{ display:inline-block; width:300px; height:300px; border:2px solid
      #ccc; position:relative; } .box1 .cube1{ position:absolute; width:100px;
      height:100px; border:1px solid red; background-color:rgba(100,10,10,.25);
      display:none; } .box1 img{ width:100%; height:100%; vertical-align:bottom;
      } .box2{ width:400px; height:400px; border:1px solid #ccc; position:absolute;
      left:350px; top:0; overflow:hidden; display:none; } .box2 img{ width:1200px;
      height:1200px; position:absolute; }
    </style>
  </head>
  
  <body>
    <div class="container">
      <div class="box1">
        <div class="cube1">
        </div>
        <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523339803140&di=005a31ed1bafedb7bebbc5cf59b85eee&imgtype=0&src=http%3A%2F%2Fwww.tianqi.com%2Fupload%2Farticle%2F16-05-26%2FKTRx_160526080616_1.png"
        alt="" />
      </div>
      <div class="box2">
        <img src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523339803140&di=005a31ed1bafedb7bebbc5cf59b85eee&imgtype=0&src=http%3A%2F%2Fwww.tianqi.com%2Fupload%2Farticle%2F16-05-26%2FKTRx_160526080616_1.png"
        alt="" class="cube2" />
      </div>
    </div>
  </body>
  <script>
    ; (function() {
      var box1 = document.querySelector('.box1');
      var cube1 = document.querySelector('.cube1');
      var box2 = document.querySelector('.box2');
      var cube2 = document.querySelector('.cube2');

      box1.onmouseover = function() {
        cube1.style.display = box2.style.display = "block";
      }
      box1.onmouseout = function() {
        cube1.style.display = box2.style.display = "none";
      }
      box1.onmousemove = function(e) {
        var left = e.clientX - box1.offsetLeft - cube1.offsetWidth / 2;
        var top = e.clientY - box1.offsetTop - cube1.offsetHeight / 2;
        if (left <= 0) left = 0;
        if (top <= 0) top = 0;
        if (left >= box1.offsetWidth - cube1.offsetWidth - 4) {
          left = box1.offsetWidth - cube1.offsetWidth - 4
        }
        if (top >= box1.offsetHeight - cube1.offsetHeight - 4) {
          top = box1.offsetHeight - cube1.offsetHeight - 4
        }
        cube1.style.left = left + 'px';
        cube1.style.top = top + 'px';

        var percentX = left / (box1.offsetWidth - cube1.offsetWidth),
        percentY = top / (box1.offsetHeight - cube1.offsetHeight);

        cube2.style.left = -percentX * (cube2.offsetWidth - box2.offsetWidth) + 'px';
        cube2.style.top = -percentY * (cube2.offsetHeight - box2.offsetHeight) + 'px';

      }
    })()
  </script>

</html>